package com.bianguo.android.pigeondemo.Presenter;

import com.bianguo.android.pigeondemo.model.BaseModel;
import com.bianguo.android.pigeondemo.view.IBaseView;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2018/6/4.
 */

public class BasePresenter<V extends IBaseView, M extends BaseModel> {

    protected WeakReference<V> mReference;
    protected HashMap<String, Disposable> disposables;
    protected M mModel;

    public BasePresenter(V mView) {
        mReference = new WeakReference<V>(mView);
        disposables = new HashMap<>();
    }

    public V getView() {
        if (mReference == null) {
            return null;
        }
        return mReference.get();
    }

    public void detach() {
        Iterator<Map.Entry<String, Disposable>> iterator = disposables.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Disposable> entry = iterator.next();
            Disposable disposable = entry.getValue();
            boolean disposed = disposable.isDisposed();
            if (disposable != null && !disposed) {
                disposable.dispose();
            }
        }
        if (mReference != null) {
            mReference.clear();
            mReference = null;
        }
    }
}
